﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using GDCal.vo;
using ESRI.ArcGIS.GISClient;
using ESRI.ArcGIS.esriSystem;

namespace GDCal
{
    public partial class AddServerForm : GDBaseForm
    {
        private ArcGISServerInfoVO arcGISServerInfoVO;
        private GDCal parentForm;
        private TreeNodeCollection nodeCollection;

        public AddServerForm(GDCal parentForm)
        {
            InitializeComponent();
            this.internetRadioButton.Select();
            this.ActiveControl = internetURLTextbox;

            //init return object
            arcGISServerInfoVO = new ArcGISServerInfoVO();

            //set parent control
            this.parentForm = parentForm;
            this.nodeCollection = parentForm.getTreeNodeCollection();
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void localRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            setAuthenticationGroupStatus(false);
            this.ActiveControl = localHostNameTextbox;
        }

        private void internetRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            setAuthenticationGroupStatus(true);
            this.ActiveControl = internetURLTextbox;
        }

        private void setAuthenticationGroupStatus(Boolean enable)
        {
            userNameLabel.Enabled = enable;
            userNameTextbox.Text = "";
            userNameTextbox.Enabled = enable;
            passwordLabel.Enabled = enable;
            passwordTextbox.Text = "";
            passwordTextbox.Enabled = enable;
            authenticationGroup.Enabled = enable;
            localHostNameTextbox.Text = "";
            localHostNameLabel.Enabled = !enable;
            localHostNameTextbox.Enabled = !enable;
            serverURLLabel.Enabled = enable;
            serverURLFormatLabel.Enabled = enable;
            internetURLTextbox.Enabled = enable;
            internetURLTextbox.Text = "";
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            this.parentForm.updateMainStatusFromDialog(GDCalMessages.Status_ConnectToServer);
            bool canConnect = false;
            if (internetRadioButton.Checked)
            {
                if (!GDCalUtils.isValueEmpty(internetURLTextbox.Text.Trim(), GDCalMessages.Notify_UrlEmpty, GDCalMessages.Notify_Caption))
                {
                    arcGISServerInfoVO.setName(getName(ArcGISServerInfoVO.ArcGIS_Server_Internet, internetURLTextbox.Text.Trim()));
                    arcGISServerInfoVO.setType(ArcGISServerInfoVO.ArcGIS_Server_Internet);
                    arcGISServerInfoVO.setUrl(internetURLTextbox.Text.Trim());
                    arcGISServerInfoVO.setUserName(userNameTextbox.Text.Trim());
                    arcGISServerInfoVO.setPassword(passwordTextbox.Text.Trim());
                }
            }
            if (localRadioButton.Checked)
            {
                if (!GDCalUtils.isValueEmpty(localHostNameTextbox.Text.Trim(), GDCalMessages.Notify_HostNameEmpty, GDCalMessages.Notify_Caption))
                {
                    arcGISServerInfoVO.setName(getName(ArcGISServerInfoVO.ArcGIS_Server_Local, localHostNameTextbox.Text.Trim()));
                    arcGISServerInfoVO.setType(ArcGISServerInfoVO.ArcGIS_Server_Local);
                    arcGISServerInfoVO.setHostName(localHostNameTextbox.Text.Trim());
                }
            }

            if (!String.IsNullOrEmpty(arcGISServerInfoVO.getName()))
            {
                if (!ifArcGisServerRegistered())
                {
                    if (ifArcGisServerCanConnect())
                        canConnect = true;
                }
            }

            if (canConnect)
                this.Close();
            else
                arcGISServerInfoVO = new ArcGISServerInfoVO();
            this.parentForm.updateMainStatusFromDialog("");
        }

        private String getName(String type, String serverNameOrUrl)
        {
            String nameToCheck = serverNameOrUrl;
            if (type.Equals(ArcGISServerInfoVO.ArcGIS_Server_Internet))
            {
                int start = serverNameOrUrl.IndexOf("//") + 2;
                int end = serverNameOrUrl.IndexOf("/", start);
                int length = end - start;
                if (start >= 0 && length >= 0)
                    nameToCheck = serverNameOrUrl.Substring(start, length);
                nameToCheck = nameToCheck.Replace(":", "_");
                nameToCheck = GDCalMessages.Internet_Arcgis_Server_Prefix + " " + nameToCheck;
            }
            return nameToCheck;
        }

        private bool ifArcGisServerRegistered() 
        {
            bool ret = false;
            String nameToCheck = arcGISServerInfoVO.getName();
            
            if (nodeCollection != null)
            {
                foreach (TreeNode node in nodeCollection)
                {
                    if (nameToCheck.Equals(node.Text, StringComparison.OrdinalIgnoreCase))
                    {
                        ret = true;
                        break;
                    }
                }
            }

            //Show message if existed
            if (ret)
                MessageBox.Show(GDCalMessages.Notify_ServerExisted, GDCalMessages.Notify_Caption);

            return ret;
        }

        private bool ifArcGisServerCanConnect()
        {
            bool ret = false;
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);

            IAGSServerConnectionFactory agsServerConnectionFactory = new AGSServerConnectionFactory();
            IPropertySet connectionProps = new PropertySet();
            IAGSServerConnection agsServerConnection = null;
            if (arcGISServerInfoVO.getType().Equals(ArcGISServerInfoVO.ArcGIS_Server_Local))
            {
                connectionProps.SetProperty("machine", arcGISServerInfoVO.getHostName());
            }
            else
            {
                connectionProps.SetProperty("URL", arcGISServerInfoVO.getUrl());
                connectionProps.SetProperty("user", arcGISServerInfoVO.getUserName());
                connectionProps.SetProperty("password", arcGISServerInfoVO.getPassword());
            }

            String errorMessage = "";
            try
            {
                agsServerConnection = agsServerConnectionFactory.Open(connectionProps, 0);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
            
            if (agsServerConnection != null) 
            {
                ret = true;
            }
            
            //Show message if can not connect
            if (!ret)
                MessageBox.Show(errorMessage, GDCalMessages.Notify_Caption);
            return ret;
        }
        
        public ArcGISServerInfoVO getArcGISServerInfo()
        {
            return arcGISServerInfoVO;
        }
    }
}
